<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>判断文件类型</title>
    <script type="text/javascript" src="../lib/fileType/FileType.js"></script>
    <script type="text/javascript" src="../lib/jquery/3.6.0/jquery-3.6.0.min.js"></script>
</head>
<body>
    <input type="file" id="file"/>
    <div>
        文件类型：<span id="file_type_text"> </span>
    </div>
    <script>
        // https://www.fly63.com/tool/filetype/
        /*const mime=[
            //type:类型，h：16字节标识【根据需要，自行添加】
            {type:'image/png',h:'89504e47'},
            {type:'image/gif',h:'47494638'},
            {type:'image/jpeg',h:'ffd8ffe0,ffd8ffe1,ffd8ffe2,ffd8ffe3,ffd8ffe8'},
            {type:'image/webp',h:'524946461c'},
            {type:'Windows Bitmap/bmp',h:'424D'},
            {type:'TIFF/tif',h:'49492A00'},
            {type:'CAD/dwg',h:'41433130'},
            {type:'Adobe Photoshop/psd',h:'384250'},
        ]
        function check(header){
            for(let i in mime){
                let arr = mime[i].h.split(',');
                let offset = (mime[i].offset || -1)+1;//偏移量
                for(let j in arr){
                    let byte=arr[j].toLowerCase().replace(/\s+/g,"");
                    if(header.indexOf(byte)==offset){
                        return mime[i].type;
                    }
                }
            }
            return 'unknown';
        }
        function loadMime(file,callback){
            let blob = file.slice(0, 128);//仅获取前128字节。
            let reader = new FileReader();
            reader.onloadend = function(e) {
                let arr = (new Uint8Array(e.target.result)).subarray(0, 200);
                let header = "";
                for(let i = 0; i < arr.length; i++) {
                    header += arr[i].toString(16);
                }
                let type=check(header);
                callback(type);
            }
            reader.readAsArrayBuffer(blob);
        }*/

        document.getElementById('file').addEventListener('change',function(e){
            var file = e.target.files[0]
            loadMime(file, function(res){
                document.getElementById("file_type_text").innerText = res.format;
                console.log("123548qeqw.".endsWith("."))
            });
        });
    </script>
</body>
</html>